<template>
  <view class="hb-flex-1 hb-h-full" @click.stop="toSearchPage">
    <view
      class="hb-h-full hb-rounded-3xl hb-transition-colors hb-duration-200 hb-flex hb-items-center hb-justify-center hb-px-4"
      :style="{ backgroundColor, color: textColor }"
    >
      <template v-if="searchVal && isShowVal">
        <view class="hb-flex-1 hb-flex hb-items-center hb-justify-between">
          <text class="hb-flex-1 text-overflow-1">{{ searchVal }}</text>
          <text
            class="ali-icon icon-guanbi1 hb-text-base hb-text-gray-300"
            @click.stop="clearVal"
          ></text>
        </view>
      </template>
      <template v-else>
        <text class="ali-icon hb-mr-1 hb-text-base">&#xe694;</text>
        <text class="hb-text-sm">{{ placeholder }}</text>
      </template>
    </view>
  </view>
</template>

<script setup lang="ts">
  import { navigateTo } from '@/router';
  import { propTypes } from '@/utils/propTypes';
  import { ref, watch } from 'vue';

  const props = defineProps({
    modelValue: propTypes.string,
    backgroundColor: propTypes.string.def('rgba(242, 243, 245, 1)'),
    textColor: propTypes.string.def('#999996'),
    placeholder: propTypes.string.def('搜索'),
    isShowVal: propTypes.bool.def(true),
  });

  const emit = defineEmits(['confirm', 'update:modelValue', 'clear']);
  const searchVal = ref('');

  watch(
    () => props.modelValue,
    (val) => {
      searchVal.value = val;
    },
    {
      immediate: true,
    },
  );

  function toSearchPage() {
    navigateTo({
      name: 'searchPage',
      options: {
        placeholder: props.placeholder,
        success: (val) => {
          searchVal.value = val;
          emit('update:modelValue', val);
          emit('confirm', val);
        },
      },
    });
  }

  function clearVal() {
    searchVal.value = '';
    emit('update:modelValue', '');
    emit('confirm', '');
    emit('clear', '');
  }
</script>

<style lang="scss" scoped>
  .hb-h-full {
    height: 100%;
  }
  .hb-w-full {
    width: 100%;
  }
  .hb-px-4 {
    padding-left: 32rpx;
    padding-right: 32rpx;
  }
  .hb-rounded-3xl {
    border-radius: 48rpx;
  }
  .hb-transition-colors {
    transition-property: color, background-color, border-color, text-decoration-color, fill, stroke;
    transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
    transition-duration: 150ms;
  }
  .hb-duration-200 {
    transition-duration: 200ms;
  }
  .hb-flex {
    display: flex;
  }
  .hb-items-center {
    align-items: center;
  }
  .hb-flex-1 {
    flex: 1 1 0%;
  }
  .hb-justify-center {
    justify-content: center;
  }
  .hb-text-base {
    font-size: 32rpx;
    line-height: 48rpx;
  }
  .hb-text-gray-300 {
    color: rgb(209 213 219);
  }
  .hb-text-sm {
    font-size: 28rpx;
    line-height: 40rpx;
  }
</style>
